package controller;

/*
 * Action for registering a new user.
 * Only administrator may register a new user.
 */

import helper.UserType;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import databeans.User;
import formbeans.RegisterForm;
import model.Model;
import model.UserDAO;
import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

public class RegisterAction extends Action {
	private FormBeanFactory<RegisterForm> formBeanFactory = FormBeanFactory.getInstance(RegisterForm.class);
	private UserDAO userDAO;
	
	public RegisterAction(Model model) {
		userDAO = model.getUserDAO();
	}
    
	public String getName() {
		return "register.do";
	}
    
    public String perform(HttpServletRequest request) {

        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        try {
        	// First, validate whether admin is accessing this
        	HttpSession session = request.getSession(false);
        	User user = (User) session.getAttribute("user");
        	
        	if (user.getType() != UserType.ADMIN) {
        		errors.add("You are not an admin!");
        		return "homepage.jsp";
        	}
        	String button = request.getParameter("button");
    		if(button.equals("Back")) return "admin.jsp";
        	
        	RegisterForm form = formBeanFactory.create(request);
        	request.setAttribute("registerform",form);
        	
        	if (!form.isPresent()) {
        		return "register.jsp";
        	}
        	
    		// Validate for errors in the form
    		errors.addAll(form.checkRegisterFormErrors());
    		if (errors.size() != 0) {
    			return "register.jsp";
    		}
    	
    		
    		// Make a new user with given info
    		User newUser = new User(form.getUserid());
    		newUser.setPassword(form.getPassword());
    		if (form.getType().equals("Researcher"))
    			newUser.setType(UserType.RESEARCHER);
    		else
    			newUser.setType(UserType.RESPONDENT);
    		userDAO.create(newUser);
    		
			return "admin.jsp";
        } catch (DAOException e) {
        	if(e.getMessage().equals("registered"))
        		errors.add("The user has already registered.");
        	return "register.jsp";
        } catch (FormBeanException e) {
        	errors.add(e.getMessage());
        	return "register.jsp";
        }
    }
}
